import { login, getProfile, getUserDetailById } from '@/api/user'
import router from '@/router'
import { removeToken } from '@/utils/auth'

const state = {
  token: localStorage.getItem('token71') || '',
  profile: {}
}

const mutations = {
  setToken(state, data) {
    state.token = data
    localStorage.setItem('token71', data)
  },
  setProfile(state, data) {
    state.profile = data
  },
  removeToken(state) {
    state.token = ''// 将vuex数据置空
    removeToken()
  },
  removeProfile(state) {
    state.profile = {} // 将vuex数据置空
  }
}

const actions = {
  async login(store, data) {
    const res = await login(data)
    store.commit('setToken', res)
  },
  async getProfile(store, data) {
    const res = await getProfile()
    const detail = await getUserDetailById(res.userId)
    store.commit('setProfile', {
      ...res,
      ...detail
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    router.push('login')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
